#!/usr/bin/env python

dbhost = "server"
dbuser = "user"
dbpasswd = "secret"
dbname = "dbname"

email = "used@gmail.com"
blogid = "xxxxxxxxxxxxxxxxxxx"
author = "Author"

#### Import from mysql

import _mysql

db = _mysql.connect(dbhost, dbuser, dbpasswd, dbname)

def save_table(table):
    print "Saving %s..." % (table)
    db.query("SELECT * FROM %s" % (table))
    r = db.store_result()
    t = r.fetch_row(how=1)
    all = []
    while t:
        all.append(t[0])
        t = r.fetch_row(how=1)
    print "table %s with %d imported" % (table, len(all))
    return all

posts = save_table("textpattern")


#### Export to blogger 

from gdata import service
import gdata
import atom
import getopt
import sys
import getpass
from datetime import datetime, timedelta


s = service.GDataService(email, getpass.getpass())
s.source = 'Textpattern to Blogger Importer'
s.service = 'blogger'
s.server = 'www.blogger.com'
s.ProgrammaticLogin()

feed = s.GetFeed('/feeds/' + blogid + '/posts/default')
print 'Blog title:', feed.title.text


done = {}
try:
    for lines in file("log").readlines():
        done[lines.split()[1]] = True
except:
    pass
log = file("log", "a")

for p in posts:
    if p['uid'] in done:
        print '>> Skip', p['Title'], 'Posted:', p['Posted']
        continue
    print '>>', p['Title'], len(p['Body_html']), 'Posted:', p['Posted'], 'Feed:', p['feed_time'], 'Modified:', p['LastMod']
    entry = gdata.GDataEntry()
    entry.author.append(atom.Author(atom.Name(text=author)))
    entry.title = atom.Title(title_type='xhtml', text=p['Title'])
    entry.content = atom.Content(content_type='html', text=p['Body_html'].decode('latin_1'))
    pdate, ptime = p['Posted'].split()
    pdate = [int(i) for i in pdate.split('-')]
    ptime = [int(i) for i in ptime.split(':')]
    posted = datetime(pdate[0], pdate[1], pdate[2], ptime[0], ptime[1], ptime[2])-timedelta(0,5*60*60)
    posted = posted.timetuple()
    posted = '%4d-%02d-%02dT%02d:%02d:%02dZ' % (posted[0], posted[1], posted[2], posted[3], posted[4], posted[5])
    entry.published = atom.Published(posted)
    # Make it a draft
    if int(p['Status']) != 4:
        entry.control = atom.Control()
        entry.control.draft = atom.Draft(text='yes')

    # Ask the service to insert the new entry.
    r = s.Post(entry, '/feeds/' + blogid + '/posts/default')
    h = r.GetEditLink().href
    try:
        s.Get(h)
    except service.RequestError:
        print "We reached the daily limit. Stop."
        break
    print >>log, "URL:", p['uid']
log.close()
